package com.wedo.mall.activity.user;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.e.library.activity.EActivity;
import com.e.library.http.EApi;
import com.e.library.http.EClient;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.e.library.utils.EStack;
import com.e.library.utils.EUtils;
import com.e.library.utils.EViewUtils;
import com.e.library.widget.ETitleBar;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.wedo.mall.R;
import com.wedo.mall.activity.MainActivity;
import com.wedo.mall.adapter.ConversationAdapter;
import com.wedo.mall.entity.MessageItem;
import com.wedo.mall.util.DateUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class MessageActivity extends EActivity implements XRecyclerView.LoadingListener,View.OnClickListener{

    @BindView(R.id.title_bar) ETitleBar title_bar;
    @BindView(R.id.rv_list)   XRecyclerView rv_list;

    private ConversationAdapter mAdapter;

    private TextView tv_systemtitle;
    private TextView tv_systemtime;
    private TextView tv_ordertitle;
    private TextView tv_ordertime;

    @Override
    protected int layout() {
        return R.layout.activity_message;
    }

    @Override
    protected void onActivityCreated(Bundle state) {

        View header = LayoutInflater.from(this).inflate(R.layout.header_message, null);

        tv_systemtitle = (TextView) header.findViewById(R.id.tv_systemtitle);
        tv_systemtime = (TextView) header.findViewById(R.id.tv_systemtime);
        tv_ordertitle = (TextView) header.findViewById(R.id.tv_ordertitle);
        tv_ordertime = (TextView) header.findViewById(R.id.tv_ordertime);

        header.findViewById(R.id.rl_systemmessage).setOnClickListener(this);
        header.findViewById(R.id.rl_ordermessage).setOnClickListener(this);

        rv_list.setHasFixedSize(true);
        EViewUtils.vertical(rv_list);
        rv_list.setLoadingMoreEnabled(false);
        rv_list.setLoadingListener(this);
        mAdapter = new ConversationAdapter(this,new ArrayList<EMConversation>());
        mAdapter.listener(this);
        rv_list.setAdapter(mAdapter);
        rv_list.addHeaderView(header);

        title_bar.setOnBackwarListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EStack.onBackPressed(MessageActivity.this, MainActivity.class.getName());
                defaultFinish();
            }
        });

    }

    @OnClick(R.id.tv_forward)
    protected void onContactClick(){
        toActivity(ContactActivity.class);
    }

    private void messages(){
        EClient.with().post(EApi.USER_MESSAGE, new EObserver() {
            @Override
            public void successful(EResponse response) {

                MessageItem messageSystem = response.object("system",MessageItem.class);
                if(messageSystem != null){
                    tv_systemtitle.setText(messageSystem.getTitle());
                    tv_systemtime.setText(DateUtils.convert( new SimpleDateFormat("yyyy-MM-dd"),Integer.valueOf(messageSystem.getAdd_time()).intValue()));
                }
                MessageItem messageOrder = response.object("order",MessageItem.class);
                if(messageOrder != null){
                    tv_ordertitle.setText(messageOrder.getTitle());
                    tv_ordertime.setText(DateUtils.convert( new SimpleDateFormat("yyyy-MM-dd"),Integer.valueOf(messageOrder.getAdd_time()).intValue()));
                }

                onRefreshComplete();
            }

            @Override
            public void failure(String msg) {
                onRefreshComplete();
            }

        });
    }

    protected List<EMConversation> conversation(){
        // get all conversations
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        /**过滤掉系统消息*/
        conversations.remove(EaseConstant.ADMIN);
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        /**
         * lastMsgTime will change if there is new message during sorting
         * so use synchronized to make sure timestamp of last message won't change.
         */
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sort(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }

    private void sort(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first.equals(con2.first)) {
                    return 0;
                } else if (con2.first.longValue() > con1.first.longValue()) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }


    /**
     * 将系统消息设置为已读
     * @param type 7表示订单消息，8表示系统消息
     */
    private void markRead(int type){

        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(EaseConstant.ADMIN);
        if (conversation == null){
            return;
        }

        conversation.markAllMessagesAsRead();
    }

    @Override
    protected void onResume() {
        super.onResume();
        refresh();
    }

    private void refresh(){
        messages();
        mAdapter.refresh(conversation());
    }

    private void onRefreshComplete(){
        if (this.isFinishing() || rv_list == null){
            return;
        }
        rv_list.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isFinishing() || rv_list == null){
                    return;
                }
                rv_list.refreshComplete();
            }
        },2 * 1000);
    }

    @Override
    public void onRefresh() {
        refresh();
    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl_systemmessage:
                markRead(EaseConstant.TYPE_SYSTEM);
                toActivity(SystemMessageActivity.class);
                break;
            case R.id.rl_ordermessage:
                markRead(EaseConstant.TYPE_ORDER);
                toActivity(OrderMessageActivity.class);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        EStack.onBackPressed(this, MainActivity.class.getName());
        super.onBackPressed();
    }
}
